package com.demo.security;

/**
 * 十六进制编码和解码
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/16 18:10
 */
public class HexUtil {

    /**
     * 十六进制解码
     *
     * @param bytes
     * @return
     */
    public static String bytes2Hex(byte[] bytes) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            boolean negative = false;//是否为负数
            if (b < 0) {
                negative = true;
            }
            int inte = Math.abs(b);
            if (negative) {
                inte = inte | 0x80;
            }
            String temp = Integer.toHexString(inte & 0xFF);
            if (temp.length() == 1) {
                stringBuilder.append("0");
            }
            stringBuilder.append(temp.toLowerCase());
        }
        return stringBuilder.toString();
    }

    /**
     * 十六进制编码
     *
     * @param content
     * @return
     */
    public static byte[] hex2bytes(String content) {
        byte[] bytes = new byte[content.length() / 2];
        for (int i = 0; i < content.length(); i = i + 2) {
            String subStr = content.substring(i, i + 2);
            boolean negative = false;//是否为负数
            int inte = Integer.parseInt(subStr, 16);
            if (inte > 127) negative = true;
            if (inte == 128) {
                inte = -128;
            } else if (negative) {
                inte = 0 - (inte & 0x7F);
            }
            byte b = (byte) inte;
            bytes[i / 2] = b;
        }
        return bytes;
    }




}
